import { createRouter, createWebHashHistory } from "vue-router";
import systemRouter from "./systemRouter";
import config from "@/config/index";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import tool from "@/utils/tool";
import { ElNotification } from "element-plus";
import { treeFilter, filterAsyncRouter, flatAsyncRoutes } from "./helper";
import { beforeEach, afterEach } from "./scrollBehavior";
import userRoutes from "@/config/route";

//系统路由
const routes = systemRouter;
//系统404路由
const routes_404 = {
  path: "/:pathMatch(.*)*",
  hidden: true,
  component: () => import(/* webpackChunkName: "404" */ "@/layout/other/404"),
};

//定义一个空的404路由
let routes_404_r = () => {};

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//设置系统标题
document.title = config.APP_NAME;

//判断是否已加载过动态/静态路由
var isGetRouter = false;

//设置路由权限
//路由进入
router.beforeEach(async (to, from, next) => {
  //开启进度条
  NProgress.start();

  //设置动态标题
  document.title = to.meta?.title
    ? `${to.meta.title}-${config.APP_NAME}`
    : config.APP_NAME;

  //获取token
  let token = tool.cookie.get("TOKEN");
  //判断前往的是否是登录页
  if (to.path === "/login") {
    router.addRoute(routes[0]);
    routes_404_r();
    isGetRouter = false;
    next();
    return false;
  }
  //判断当前前往的路由是否在当前路由列表中，是的话直接定向到
  if (routes.findIndex((r) => r.path === to.path) >= 0) {
    next();
    return false;
  }

  //判断token不存在跳转到登陆页
  if (!token) {
    next({
      path: "/login",
    });
    return false;
  }
  //整页路由处理
  if (to.meta.fullpage) {
    to.matched = [to.matched[to.matched.length - 1]];
  }
  //加载动态路由

  if (!isGetRouter) {
    //初次判断加载动态路由
    //异步接口路由
    let asyncMenu = tool.data.get("MENU") || [];
    //用户信息
    let userInfo = tool.data.get("USER_INFO");

    // 项目配置的静态路由
    let userMenu = treeFilter(userRoutes, (node) => {
      return node.meta.role
        ? node.meta.role.filter((item) => userInfo.role.indexOf(item) > -1)
            .length > 0
        : true;
    });

    let menu = [...userMenu, ...asyncMenu];

    let menuRouter = filterAsyncRouter(menu);
    menuRouter = flatAsyncRoutes(menuRouter);

    menuRouter.forEach((item) => {
      router.addRoute("layout", item);
    });
    routes_404_r = router.addRoute(routes_404);

    //通过to.matched 这个记录是否为空来判断是否跳转
    if (to.matched.length == 0) {
      router.push(to.fullPath);
    }

    isGetRouter = true;
  }
  beforeEach(to, from);
  next();
});

//路由离开
router.afterEach((to, from) => {
  afterEach(to, from);
  NProgress.done();
});

//路由报错
router.onError((error) => {
  NProgress.done();
  ElNotification.error({
    title: "路由错误",
    message: error.message,
  });
});

const sc_getMenu = () => {
  var apiMenu = tool.data.get("MENU") || [];
  let userInfo = tool.data.get("USER_INFO");
  let userMenu = treeFilter(userRoutes, (node) => {
    return node.meta.role
      ? node.meta.role.filter((item) => userInfo.role.indexOf(item) > -1)
          .length > 0
      : true;
  });
  var menu = [...userMenu, ...apiMenu];
  return menu;
};

//入侵追加自定义方法、对象
router.sc_getMenu = sc_getMenu;

export default router;
